package libs

import (
	"github.com/disintegration/imaging"

	"net/http"
	"os"
	"strconv"
	"strings"
)

func FileExt(file string) string {
	f := strings.Split(file, ".")
	return f[len(f)-1]
}
func IsImg(fileExt string) bool {
	f := strings.Split(fileExt, "!")
	imgExt := []string{"jpg", "jpeg", "png", "gif", "bmp"}
	for _, v := range imgExt {
		if f[0] == v {
			return true
		}
	}
	return false
}

func DownloadHandler(w http.ResponseWriter, r *http.Request) {
	//fmt.Printf("%q\n", strings.Split(r.URL.Path, "/"))
	r.URL.Path = strings.Replace(r.URL.Path, "/k", "", -1)
	url := strings.Split(r.URL.Path, "/")
	//path := url[3]
	//r.URL.Path = "/"+path
	//fmt.Println(r.URL.Path)
	r.URL.Path = r.URL.Path[1:3] + "/" + r.URL.Path[3:5] + "/" + r.URL.Path[5:7] + r.URL.Path

	//直接给原地址或压缩地址，发现没有的时候才判断是图片还是文件，如果原来是图片，那就生成缩略图
	if IsImg(FileExt(r.URL.Path)) {
		//判定是否缩略图
		thumb_sub := strings.Split(url[len(url)-1], "!")
		//fmt.Println(r.URL.Path,thumb_sub)
		if len(thumb_sub) == 2 {
			thumb_size := strings.Split(thumb_sub[1], "_")
			r.URL.Path = strings.Replace(r.URL.Path, "!"+thumb_sub[1], "", 1)
			if len(thumb_size) == 2 {
				thumbPath := Conf.DirThumb + thumb_sub[1] + "/" + r.URL.Path
				//fmt.Println(thumbPath,r.URL.Path)
				_, err := os.Stat(thumbPath)
				if err != nil {
					if os.IsNotExist(err) {
						originalPath := Conf.DirUpload + r.URL.Path
						//fmt.Println(originalPath,thumbPath)
						thumb_width, _ := strconv.Atoi(thumb_size[0])
						thumb_height, _ := strconv.Atoi(thumb_size[1])

						if FileExt(r.URL.Path) == "gif" {
							img, err := GifResize(originalPath, thumb_width, thumb_height)
							if err != nil {
								//fmt.Println(err)
								http.Error(w, http.StatusText(404), http.StatusNotFound)
								return
							}
							MkdirByFile(thumbPath)
							GifSave(img, thumbPath)
						} else {
							//fmt.Println(originalPath,thumbPath)
							img, err := imaging.Open(originalPath)
							if err != nil {
								http.Error(w, http.StatusText(404), http.StatusNotFound)
								return
							}
							//fmt.Println(thumbnails_width,thumbnails_height)
							MkdirByFile(thumbPath)
							thumb := imaging.Thumbnail(img, thumb_width, thumb_height, imaging.CatmullRom)
							err = imaging.Save(thumb, thumbPath)
							if err != nil {
								//fmt.Println(err)
								http.Error(w, http.StatusText(404), http.StatusNotFound)
								return
							}
						}
					}
				}
				w.Header().Set("Content-Type", "image")
				http.ServeFile(w, r, thumbPath)
				return
			} else {
				imagePath := Conf.DirUpload + r.URL.Path
				w.Header().Set("Content-Type", "application/octet-stream")
				http.ServeFile(w, r, imagePath)
				return
			}
		} else {
			imagePath := Conf.DirUpload + r.URL.Path
			w.Header().Set("Content-Type", "image")
			http.ServeFile(w, r, imagePath)
			return
		}
	} else {
		imagePath := Conf.DirUpload + r.URL.Path
		w.Header().Set("Content-Type", "application/octet-stream")
		http.ServeFile(w, r, imagePath)
		return
	}
}
